Skip to main content

How to detect touch on 3D objects in the scene

⚠️ for it to work correctly, the object must have some type of collision ⚠️

In your Java class, do the following:

public class YourClass extends Component {

// creates a new Laser
private final Laser laser = new Laser();

// creates a new Camera, @Singleton attaches the first Camera component it finds in the scene
@Singleton
private Camera camera;

@Override
public void start() {

}

@Override
public void repeat() {

// checking whether the first touch detected on the screen is null and returning the code if it is true
if(Input.getTouch(0) == null) return;

// Vector2 responsible for storing the position of the first touch detected on the screen
Vector2 position = Input.getTouch(0).getPosition();

// the direction of the ray that will be fired from the camera at the position of the "position" variable
RayDirection rayDirection = camera.screenPointRay(position);

// the ray that will be fired
Ray ray = new Ray(rayDirection, 0);

// the laser collision point
LaserHit laserHit = laser.trace(ray);

// checking if laserHit is non-null
if(laserHit != null) {

// showing the name of the object that the laser detected in the terminal if the conditional is true
Console.log("The detected object was: " + laserHit.getObject().getName());
}
}
}